package problem215;

import java.util.Random;

//215.数组中的第k个最大元素
//https://leetcode.cn/problems/kth-largest-element-in-an-array/description/

class Solution {
    public int findKthLargest(int[] nums, int k) {
        return qsort(nums, 0, nums.length-1, k);
    }
    public int qsort(int[] nums, int l, int r, int k) {
        if(l == r) return nums[l];
        int key = nums[new Random().nextInt(r-l+1)+l];
        int left = l-1, right = r+1, i = l;
        while(i < right) {
            if(nums[i] == key) i++;
            else if(nums[i] < key) swap(nums, ++left, i++);
            else if(nums[i] > key) swap(nums, --right, i);
        }
        //[l, left] [left+1, right-1] [right, r]
        int a = left-l+1, b = right-1-left, c = r-right+1;
        if(c >= k) return qsort(nums, right, r, k);
        else if(b+c >= k) return key;
        else return qsort(nums, l, left, k-b-c);
    }
    public void swap(int[] arr, int a, int b) {
        int t = arr[a];
        arr[a] = arr[b];
        arr[b] = t;
    }
}